package systempen.cmanager;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.DateTimeKeyListener;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CostList extends ListActivity {
	ListActivity thisclass;
	// private String[] lv_arr;
	public View arg;
	public int arg4;
	public ListView lv;
	public View tempArg;
	private String selectedWord = null;
	private String selectedDate = null;
	private String selectedAmount = null;
	private String selectedDescription = null;
	private String selectedPath = null;
	private String selectedType = null;
	private String selectedAccount = null;
	public String contextID; // context na koji si kliknuo
	public String fromDate;
	public String toDate;
	public String SingleCost;
	private float sumaSvega;
	private String _account;
	private String _type;
	private String _types; // all below
	private ArrayList<CostListItem> m_Devices;
	public String[] from = new String[] { "whe", "_id" };
	public int[] to = new int[] { R.id.ctgornji, R.id.ctdonji };
	private Context _contekst;
	private String selectedPicture;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		_contekst = getParent();
		if (_contekst == null)
			_contekst = this;

		DataBaseHelper dh = new DataBaseHelper(_contekst);
		dh.openDataBase();
		dh.close();
		super.onCreate(savedInstanceState);
		ThemePicker.onActivityCreateSetTheme(this);
		setContentView(R.layout.costlist);
		thisclass = this;
		lv = getListView();
		Bundle bun = getIntent().getExtras();
		if ((bun != null) && (bun.getString("SingleCost") != null)) {// if we have this data
			SingleCost = bun.getString("SingleCost").toString();
		} else
			SingleCost = "%";
		if ((bun != null) && (bun.getString("DateFrom") != null)) {// if we have this data
			fromDate = bun.getString("DateFrom").toString();
		} else
			fromDate = util.GetDefaultFromDateDB(getApplicationContext());

		if ((bun != null) && (bun.getString("DateTo") != null)) {// if we have this data
			toDate = bun.getString("DateTo").toString();
		} else
			toDate = util.GetDefaultToDateDB(getApplicationContext());

		if ((bun != null) && (bun.getString("Account") != null)) {// if we have this data
			_account = bun.getString("Account").toString();
		} else
			_account = "";
		if ((bun != null) && (bun.getString("Type") != null)) {// if we have this data
			_type = bun.getString("Type").toString();
		} else
			_type = "";
		if (!_type.equals("")) {
			_types = util.getAllChildren(_type, _contekst);
		}

		RefreshList(0);
		try {
			registerForContextMenu(lv);

			this.lv.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// Toast.makeText(deleteCosts.this,"arg0: "+arg0.toString()+" arg1:"+arg1.toString()+" arg2: "+String.valueOf(arg2)
					// +" arg3:"+String.valueOf(arg3)+ ((TextView)
					// arg1).getText() , Toast.LENGTH_SHORT).show();
					// Toast.makeText(deleteCosts.this,util.getBracketValue((String)
					// ((TextView) arg1).getText()), Toast.LENGTH_SHORT).show();
					// ////////////////////////////scary alert builder dialog
					arg = arg1;
					arg4 = arg2;
					tempArg = arg1;
					AlertDialog.Builder alt_bld = new AlertDialog.Builder(_contekst);
					alt_bld.setMessage("Are you sure you want to delete this cost?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// Action for 'Yes' Button
							try {
								// util.execSQL("delete from log where a = "+util.getBracketValue((String)
								// ((TextView) arg).getText()), thisclass);
								View v = ((RelativeLayout) tempArg).findViewById(R.id.ctcode);
								String deleted = ((TextView) v).getText().toString(); // Integer.toString(arg4);
								util.execSQL("delete from log where a = " + deleted, _contekst);
								// lv.setAdapter(null);
								RefreshList(0);
							} catch (Exception ex) {
								util.showDialog(ex.getMessage(), _contekst);
							}
						}
					}).setNegativeButton("No", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// Action for 'NO' Button
							dialog.cancel();
						}
					});
					AlertDialog alert = alt_bld.create();
					// Title for AlertDialog
					alert.setTitle("Delete cost?");
					// Icon for AlertDialog
					alert.setIcon(R.drawable.help);
					// alert.show(); //izbaceno odavde.
					// ////////////////////////////end scary alert builder
					// dialog
				}
			});
		} catch (Exception ex) {
			Toast.makeText(_contekst, "poruka:" + ex.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		try {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			RelativeLayout ln = ((RelativeLayout) info.targetView);
			View vi = ln.findViewById(R.id.ctgornji);
			selectedWord = ((TextView) vi).getText().toString();
			vi = ln.findViewById(R.id.ctdonji);
			selectedDate = ((TextView) vi).getText().toString();
			vi = ln.findViewById(R.id.ctPath);// .getChildAt(3);
			selectedPath = ((TextView) vi).getText().toString();
			vi = ln.findViewById(R.id.opis);
			selectedDescription = ((TextView) vi).getText().toString();
			vi = ln.findViewById(R.id.cifra);
			int intColor = ((TextView) vi).getCurrentTextColor();
			String strColor = String.format("#%06X", 0xFFFFFF & intColor);
			if (strColor.equals("#FF9900")){//neka narandzasta
				selectedAmount = "-"+((TextView) vi).getText().toString();
			}else
			{
				selectedAmount = ((TextView) vi).getText().toString();
			}
			vi = ln.findViewById(R.id.ctType);
			selectedType = ((TextView) vi).getText().toString();
			vi = ln.findViewById(R.id.ctcode);
			String code = ((TextView) vi).getText().toString();
			selectedAccount = util.getAccountNameFromCode(code, getApplicationContext());
			vi = ln.findViewById(R.id.picture_param);
			selectedPicture = ((TextView) vi).getText().toString();

			contextID = ((TextView) ln.findViewById(R.id.ctcode)).getText().toString();
			// selectedWordId = info.id;
			menu.setHeaderTitle(selectedWord);
			// menu.add(0,v.getId(),0,"Assign type to cost");
			menu.add(0, v.getId(), 0, "Delete cost");
			menu.add(0, v.getId(), 0, "Modify data");
		} catch (Exception ex) {
			Toast.makeText(_contekst, "FFS cr context: " + ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	public void onNewTransaction(View view) {
		startActivity(new Intent(_contekst, MainActivityTab.class));
	}

	public void onDayBefore(View view) {
		if (fromDate.equals(toDate.toString())) {
			fromDate = util.getDayBeforeDB(fromDate, _contekst);
			toDate = util.getDayBeforeDB(toDate, _contekst);
			RefreshList(0);
		} else {
			fromDate = util.getYesterdayDB();
			toDate = util.getYesterdayDB();
			RefreshList(0);
		}

	}

	public void onChangePeriod(View view) {
		// Toast.makeText(this, "Implemented!", Toast.LENGTH_SHORT).show();
		final CharSequence[] items = { "This month", "Last month", "Today", "All time", "This week", "Last week", "Last 2 weeks" };

		AlertDialog.Builder builder = new AlertDialog.Builder(_contekst);
		builder.setTitle("Choose period");
		builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				if (items[item].equals("This month")) {
					fromDate = util.GetThisMonthPeriodDB().a.toString();
					toDate = util.GetThisMonthPeriodDB().b.toString();
					RefreshList(0);
				}
				if (items[item].equals("Last month")) {
					fromDate = util.GetLastMonthPeriodDB().a.toString();
					toDate = util.GetLastMonthPeriodDB().b.toString();
					RefreshList(0);
				}
				if (items[item].equals("Today")) {
					fromDate = util.GetTodayPeriodDB().a.toString();
					toDate = util.GetTodayPeriodDB().b.toString();
					RefreshList(0);
				}
				if (items[item].equals("All time")) {
					fromDate = "1900-01-01";
					toDate = "3000-01-01";
					RefreshList(0);
				}
				if (items[item].equals("This week")) {
					fromDate = util.GetThisWeekPeriodDB().a.toString();
					toDate = util.GetThisWeekPeriodDB().b.toString();
					RefreshList(0);
				}
				if (items[item].equals("Last week")) {
					fromDate = util.GetLastWeekPeriodDB().a.toString();
					toDate = util.GetLastWeekPeriodDB().b.toString();
					RefreshList(0);
				}
				if (items[item].equals("Last 2 weeks")) {
					fromDate = util.GetLast2WeekPeriodDB().a.toString();
					toDate = util.GetLast2WeekPeriodDB().b.toString();
					RefreshList(0);
				}
				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	// pressed back button cya
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			startActivity(new Intent(_contekst, MainActivityTab.class));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getTitle() == "Delete cost") {
			contextDelete(contextID);
		} else if (item.getTitle() == "Modify data") {
			modifyData();
		} else {
			return false;
		}
		return true;
	}

	public void modifyData() {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(_contekst, ConfirmInsert.class.getName());
			Bundle bun = new Bundle();
			bun.putString("operation", "Update");
			bun.putString("a", contextID);// ovo je kljuc za update
			bun.putString("cost_code", selectedType);// ovo je kljuc za update,cod nemam

			float num = util.getNumber("", selectedAmount);
			selectedAmount = Float.toString(num);
			/*
			// ako ima viska zareza, zdravo!
			if (selectedAmount.contains(",") && ((selectedAmount.toString().contains(".")))) {
				selectedAmount = selectedAmount.toString().replaceFirst(",", "");
			}
			if (selectedAmount.toString().contains(",") && ((selectedAmount.toString().contains(".")))) {
				selectedAmount = selectedAmount.toString().replaceFirst(",", "");
			}
			if (selectedAmount.toString().contains(",") && ((selectedAmount.toString().contains(".")))) {
				selectedAmount = selectedAmount.toString().replaceFirst(",", "");
			}
			 */

			bun.putString("value", selectedAmount);
			bun.putString("whe", selectedDate);
			bun.putString("description", selectedDescription);
			bun.putString("path", selectedPath.toString()); // i ovo treba dodati
			bun.putString("account", selectedAccount);// debug
			bun.putString("picture", selectedPicture);//indicates that picture exists
			if (selectedPicture.equals("+Picture")){//picture exists, find it and fill shared prefs
				String pictureName = util.getFirstDataString("select picture from log where a = "+contextID, getApplicationContext());
				SharedPreferences prefs = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
				SharedPreferences.Editor ed = prefs.edit();
				ed.putString("PictureName", pictureName); //picture name
				ed.putBoolean("PictureExists", true); //picture name
				ed.commit(); 
			}
			intent.putExtras(bun);
			_contekst.startActivity(intent);
		} catch (Exception ex) {
			Toast.makeText(_contekst, ex.getMessage(), Toast.LENGTH_SHORT).show();
		}

	}

	public void contextDelete(String title) {
		// /////////////////////////////////////////////////////////delete begin
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(_contekst);
		alt_bld.setMessage("Are you sure you want to delete this cost?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// Action for 'Yes' Button
				try {
					util.execSQL("delete from log where a = " + contextID, _contekst);
					lv.setAdapter(null);
					RefreshList(0);// functions like refresh();
				} catch (Exception ex) {
					util.showDialog(ex.getMessage(), _contekst);
				}
			}
		}).setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// Action for 'NO' Button
				dialog.cancel();
			}
		});
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle("Delete cost?");
		// Icon for AlertDialog
		alert.setIcon(R.drawable.help);
		alert.show();
		// ////////////////////////////end scary alert builder dialog
		// /////////////////////////////////////////////////////////delete end
	}

	public String getPathOfLevel(String levelID) {// trebalo mi je 4 sata za
		// ovo, al sam izlapio...
		// note to self: sledeci put
		// iskopiraj, konju!
		String parent = util.parentLevelExists(levelID, _contekst);
		if (parent != "") {// ako postoji parent daj ga ako ne onda to je to
			String povratni = getPathOfLevel(parent) + " > " + util.getLevelName(levelID, _contekst);
			return povratni;
		} else {
			if (levelID.equals("0")) {
				levelID = "Root";
			}
			return levelID;
		}
	}

	public void RefreshList(int costNumber) {
		try {
			String sqlaccount, defaultAccount;
			defaultAccount = util.getDefaultAccountCode(getApplicationContext());
			sqlaccount = "";
			if ((_account != null) && (!_account.equals("") && (!_account.equals("0")))) {
				sqlaccount = " and ifnull(log.account," + defaultAccount + ") = " + _account;
			} else {
				_account = "";
			}
			String sqlTypes;
			if ((_types != null) && (!_types.equals(""))) {
				sqlTypes = " and cost_code in (" + _types + ") ";
			} else {
				sqlTypes = "";
			}

			m_Devices = new ArrayList<CostListItem>();
			sumaSvega = 0;
			thisclass = this;
			Cursor c;
			float cumulativeSum = 0;
			String sqlDebug = "select whe as _id,cost_type.name, log.a as a, value, log.description, code, path, account, a.description as accountn, log.picture "
					+ " from log join cost_type on log.cost_code = cost_type.code " 
					+ " join account a on a.a = ifnull(log.account,1) " 
					+ " where whe >= '" 
					+ fromDate + "'"
					+ " and whe <='" 
					+ toDate + "'" 
					+ " and cost_code like '" 
					+ SingleCost.toString() 
					+ "'" 
					+ sqlTypes 
					+ sqlaccount
					+ " order by whe, a ";
			util u = new util();
			c = u.getCursor(sqlDebug, _contekst);
			c.moveToFirst();
			java.util.Date d = new java.util.Date();
			if (c.getCount() > 0) {
				if (c.moveToFirst()) {
					CostListItem listItem;
					d = new java.util.Date();
					do {
						cumulativeSum = cumulativeSum + Float.valueOf(c.getString(3).trim()).floatValue();
						String mC = c.getString(0);
						String cc = util.customFormat("###,##0.00", Float.valueOf(c.getString(3).trim()).floatValue());
						String cu = util.customFormat("###,##0.00", cumulativeSum);
						sumaSvega = sumaSvega + Float.valueOf(c.getString(3).trim()).floatValue();
						String gornji = c.getString(1);
						String donji = util.dbStringDateToViewStringDate(c.getString(0), getApplicationContext());// c.getString(0);
						String code = c.getString(2);
						String cifra = cc;
						String opis = c.getString(4);
						String type = c.getString(5);
						String path = c.getString(6);// getPathOfLevel(type);
						String account = c.getString(8);
						String picture = c.getString(9);
						listItem = new CostListItem();// ListItemL(gornji,donji,code,cifra,opis,type,path,"");
						listItem.setGornji(gornji);
						listItem.setDonji(donji);
						listItem.setCode(code);
						listItem.setCifra(cifra);
						listItem.setOpis(opis);
						listItem.setType(type);
						listItem.setPath(path);
						listItem.setOpis2(account);
						listItem.setPicture(picture);
						listItem.setCumulativeSum(cu);
						m_Devices.add(listItem);
					} while (c.moveToNext());
				}
			}
			c.close();
			u.db.close();
			Log.e("ttag", new java.util.Date().toString());
			CostListAdapter adapter = new CostListAdapter(_contekst, R.layout.costlist_row, m_Devices);
			setListAdapter(null);
			adapter.notifyDataSetChanged();
			setListAdapter(adapter);
			lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
			TextView t = (TextView) findViewById(R.id.textSumaSvega);
			if (sumaSvega < 0)
			{
				t.setTextColor(getApplicationContext().getResources().getColor(R.color.ColMoney));
				sumaSvega = (-1*sumaSvega);//hide negative number
			}else
			{
				t.setTextColor(getApplicationContext().getResources().getColor(R.color.ColRed));
			}
			t.setText(util.customFormat("###,##0.00", sumaSvega));
			TextView txtTotal = (TextView) findViewById(R.id.txtDate);
			if (fromDate.equals(toDate)) {
				txtTotal.setText("Sum for day: " + util.dbStringDateToViewStringDate(fromDate, _contekst));
			} else
				txtTotal.setText("Sum for period: " + util.dbStringDateToViewStringDate(fromDate, _contekst) + '-' + util.dbStringDateToViewStringDate(toDate, _contekst));

		}// od try

		catch (Exception ex) {
			Toast.makeText(_contekst, "Delete cost error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
}
